package com.clip.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.jml.MsnContact;
import net.sf.jml.MsnMessenger;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.clip.action.util.SessionAttributeKey;
import com.clip.entity.Contact;
import com.clip.entity.ContactGroup;
import com.clip.entity.ContactGroupMapping;
import com.clip.entity.EmailSubscribe;
import com.clip.entity.User;
import com.clip.entity.UserEmail;
import com.clip.entity.UserEmailCollection;
import com.clip.entity.Usermobileinfo;
import com.clip.service.ContactGroupService;
import com.clip.service.ContactService;
import com.clip.service.UserEmailService;
import com.clip.service.UserService;
import com.clip.service.UsermobileinfoService;
import com.clip.util.Struts2Utils;
import com.clip.util.ToolsUtils;
import com.clip.util.mail.MsnBasicMessenger;
import com.opensymphony.xwork2.ActionSupport;

@Controller
@Scope("prototype")
public class ContactAction extends ActionSupport{
	private static final long serialVersionUID = 1738157010513905406L;

	@Autowired
	private ContactService contactService;
	@Autowired
	private UserEmailService userEmailService;
	@Autowired
	private UserService userService;
	@Autowired
	private ContactGroupService contactGroupService;
	@Autowired
	private UsermobileinfoService usermobileinfoService;
	
	private final String emailRegex="^([\\w\\-\\.]+)@((\\[([0-9]{1,3}\\.){3}[0-9]{1,3}\\])|(([\\w\\-]+\\.)+)([a-zA-Z]{2,4}))$";
	
	private String id;
	private String contactName;
	private String contactEmail;
	private String contactType;
	private String content;
	
	private String jaction;
	
	private String emailInput;
	private String pwdInput;
	private String pwdInput2;
	private String nameInput;
	private String vcodeInput;
	
	private String msnName;
	private String msnPwd;
	
	private String namelist; // , 分割
	private String emaillist; // , 分割
	
	private int currentpage;
	
	private String groupname;
	private int groupid;
	private String contacts;
	private int uid;
	private int requestuid;
	private int responsestatus;
	private String subscribeemail;
	private String optcode;
	
	private final int EMAILSUBSCRIBEPAGELENGTH=15;
	/**
	 * 好友请求处理
	 * 处理注册联系人请求
	 */
	public void doRegisterContact(){
		String result = "";
		content = ToolsUtils.htmlEnCode(content);
		HttpServletRequest request = ServletActionContext.getRequest();
		if(content!=null&&content!=""){
			if(jaction.equals("loadRquestInfo")){
				result = contactService.loadRegRequestInfo(content);
			}else if(jaction.equals("register")){
				String verifyCode = (String)request.getSession().getAttribute("verifyCode");
				if(vcodeInput.toLowerCase().equals(verifyCode.toLowerCase())&&emailInput.matches(emailRegex)){
					result = userService.inviteRegister(content,emailInput,ToolsUtils.htmlEnCode(nameInput),pwdInput,id);
				}else{
					//验证码错误
					result = "<root><message>验证码错误</message></root>";
				}
			}else if(jaction.equals("login")){
				String bind = request.getParameter("bind");
				String addftg = request.getParameter("addftg");
				result = userService.inviteLogin(content,emailInput,pwdInput,bind,addftg);
			}
		}
		Struts2Utils.renderXml(result);
	}

	/**
	 * 好友请求处理
	 * 处理用户联系人请求
	 */
	public void doUserContact(){
		String result = "";
		content = ToolsUtils.htmlEnCode(content);
		if(content!=null&&content!=""){
			if(jaction.equals("loadRquestInfo")){
				result = contactService.loadRquestInfo(content);
			}else if(jaction.equals("agree")){
				result = contactService.agree(content);
			}else if(jaction.equals("refuse")){
				result = contactService.refuse(content);
			}
		}
		Struts2Utils.renderXml(result);
	}
	
	public void responseContactRequest(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User currentUser = (User) session.getAttribute(SessionAttributeKey.USER);
		String re=this.contactService.addContact(currentUser,requestuid,responsestatus);
		JSONObject reObj=new JSONObject();
		if(re==null){
			reObj.put("result", 1);
		}else{
			reObj.put("result", 0);
			reObj.put("errormsg", re);
		}
		Struts2Utils.renderJson(reObj.toString());
	}
	/**
	 * 添加联系人
	 */
	public void addContact(){
		String result="{result:'输入不完整',flag:0}";
		HttpSession session=ServletActionContext.getRequest().getSession();
		User user = (User) session.getAttribute(SessionAttributeKey.USER);
		if(ToolsUtils.searchEmpty(this.contactEmail,this.contactType,this.contactName).size()<=0&&user!=null){
			//String nameRegex="^[A-Za-z0-9\u4e00-\u9fa5]{2,20}";
			String typeRegex="[0-9]{1,}";
			if(contactEmail.matches(emailRegex)&&contactType.matches(typeRegex)){
				String tmp=ToolsUtils.htmlEnCode(contactName);
				result = contactService.addEmailContact(user,tmp,contactEmail,Integer.valueOf(contactType),content);
			}
		}
		Struts2Utils.renderText(result);
	}
	/**
	 * 获取联系人
	 */
	public void contactInfo(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User currentUser = (User) session.getAttribute(SessionAttributeKey.USER);
		JSONObject returnObj=new JSONObject();
		if(currentUser!=null&&ToolsUtils.searchEmpty(contactType).size()<=0){
			int contacttype=Integer.parseInt(contactType);
			Long allcount=contactService.getUserContactTotalCount(currentUser, contacttype);
			int perpagelength=ContactService.CONTACTPAGINGSIZE;
			int pagecount=new Double(Math.ceil(allcount.doubleValue()/new Double(perpagelength))).intValue();
			if(currentpage<0||currentpage>=pagecount){
				currentpage=0;
			}
			List<Contact> list= contactService.getUserContact(currentUser,contacttype,currentpage);
			returnObj.put("result", 1);
			returnObj.put("pagecount", pagecount);
			returnObj.put("currentpage", currentpage);
			JSONArray array=new JSONArray();
			for (Contact contact : list) {
				JSONObject temp=new JSONObject();
				temp.put("contactid", contact.getId());
				temp.put("contactname", contact.getName());
				if(contacttype==0){
					temp.put("status", 1);
					int contactuid=contact.getContactuid();
					temp.put("contactuid", contactuid);
					List emaillist=this.userEmailService.getAvaiableUserEmailbyUid(contactuid);
					if(emaillist!=null&&emaillist.size()>0){
						UserEmail userEmail=(UserEmail) emaillist.get(0);
						temp.put("email", userEmail.getEmail());
					}else{
						temp.put("email", "");
					}
					Usermobileinfo usermobileinfo=this.usermobileinfoService.getBindableMobile(contactuid);
					if(usermobileinfo!=null&&usermobileinfo.getStatus()==1){
						temp.put("mobilenum", usermobileinfo.getMobilenum());
					}else{
						temp.put("mobilenum", "");
					}
					User contactuser=this.userService.getUserById(contactuid);
					int sex=contactuser.getSex()==null?0:contactuser.getSex();
					long birth=contactuser.getBirth()==null?0l:contactuser.getBirth();
					String qq=contactuser.getQq();
//					String msn=contactuser.getMsn();
//					String living=contactuser.getLiving();
//					String blog=contactuser.getBlog();
					List logolist=this.userService.getUserLogoByUid(contactuid);
					temp.put("name", contactuser.getName());
					temp.put("sex", sex);
					temp.put("birth", birth);
					temp.put("qq", qq);
					temp.put("userlogo", logolist.get(0));
				}else{
					temp.put("status", 0);
				}
				
				array.add(temp);
			}
			returnObj.put("contacts", array);
		}else{
			returnObj.put("result", 0);
			returnObj.put("errormsg", "数据错误");
		}
		Struts2Utils.renderJson(returnObj.toString());
	}
	
	public void getAllSubscribedUsers(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User currentUser = (User) session.getAttribute(SessionAttributeKey.USER);
		JSONObject jsonObject=new JSONObject();
		int showtype=Integer.parseInt(this.contactType);
		if(showtype==1){
			List list=this.contactService.getAllSubscribedUsers(currentUser.getId(),currentpage,ContactService.CONTACTPAGINGSIZE);
			Long allcount=contactService.countAllSubscribedUsers(currentUser.getId(),false);
			int pagecount=new Double(Math.ceil(allcount.doubleValue()/new Double(ContactService.CONTACTPAGINGSIZE))).intValue();
			JSONArray array=new JSONArray();
			for (Object object : list) {
				Contact con=(Contact) object;
				JSONObject temp=new JSONObject();
				temp.put("contactid", con.getId());
				List emaillist=this.userEmailService.getAvaiableUserEmailbyUid(con.getContactuid());
				if(emaillist!=null&&emaillist.size()>0){
					UserEmail userEmail=(UserEmail) emaillist.get(0);
					temp.put("email", userEmail.getEmail());
				}else{
					temp.put("email", "");
				}
				User user=this.userService.getUserById(con.getContactuid());
				temp.put("uid", user.getId());
				temp.put("name", user.getName());
				temp.put("birth", user.getBirth());
				temp.put("qq", user.getQq());
				String logo=(String) UserService.getUserLogoByUid(user.getId()).get(0);
				temp.put("userlogo",logo);
				array.add(temp);
			}
			jsonObject.put("userss", array);
			jsonObject.put("allcount", allcount);
			jsonObject.put("pagecount", pagecount);
			jsonObject.put("currentpage", currentpage);
		}else{
			List list=this.contactService.getAllSubscribedEmails(currentUser.getId(),currentpage,this.EMAILSUBSCRIBEPAGELENGTH);
			Long allcount=contactService.countAllSubscribedEmails(currentUser.getId());
			int pagecount=new Double(Math.ceil(allcount.doubleValue()/new Double(ContactService.CONTACTPAGINGSIZE))).intValue();
			JSONArray array=new JSONArray();
			for (Object object : list) {
				EmailSubscribe es=(EmailSubscribe) object;
				JSONObject temp=new JSONObject();
				long sstime=es.getSstime();
				int status=es.getStatus();
				String email=es.getEmail();
				temp.put("sstime", sstime);
				temp.put("status", status);
				temp.put("email", email);
				array.add(temp);
			}
			jsonObject.put("emailss", array);
			jsonObject.put("allcount", allcount);
			jsonObject.put("pagecount", pagecount);
			jsonObject.put("currentpage", currentpage);
		}
		
		Struts2Utils.renderJson(jsonObject.toString());
	}
	/***
	 * <root>
	 *	<type>
	 *		<name></name>
	 *		<id></id>
	 *	</type>
	 * </root>
	 * 
	 */
	public void loadConTypeInfo(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User user = (User) session.getAttribute(SessionAttributeKey.USER);
		if(user!=null){
			Map<String,Object> ctMap = contactService.getContactType(user);
			Struts2Utils.renderXml(ToolsUtils.getDOM(ctMap));
		}
	}
	public void loadContactAll(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User currentUser = (User) session.getAttribute(SessionAttributeKey.USER);
		JSONObject reobj=new JSONObject();
		if(currentUser!=null){
			reobj.put("result", 1);
			List<Contact> contactlist=contactService.loadContactAll(currentUser);
			List<ContactGroup> grouplist=contactGroupService.getUserGroups(currentUser.getId());
			
			List<Contact> removeList=new ArrayList<Contact>();
			JSONArray array1=new JSONArray();
			JSONArray array2=new JSONArray();
			for(Contact con : contactlist){
				JSONObject contactobj=new JSONObject();
				int cuid=con.getContactuid();
				User cuser=this.userService.getUserById(cuid);
				if(this.userService.checkIsUser(cuser)){
					contactobj.put("name", con.getName());
					contactobj.put("pinyinname", con.getPinyinname());
//					map.put("email", con.getContactemail());
					boolean ishas=this.contactService.isHasBindableMobile(cuid);
					contactobj.put("hasmobile", ishas);
					contactobj.put("uid",cuid);
					contactobj.put("logo", UserService.getUserLogoByUid(cuid).get(1));
					array1.add(contactobj);
				}else{
					removeList.add(con);
				}
			}
			reobj.put("contactcount", array1.size());
			reobj.put("contacts", array1);
			this.contactService.updateContact(removeList);
			
			for (int i = 0; i < grouplist.size(); i++) {
				ContactGroup contactGroup=grouplist.get(i);
				JSONObject groupobj=new JSONObject();
				int groupid=contactGroup.getId();
				groupobj.put("groupid", groupid);
				groupobj.put("groupname", contactGroup.getGroupname());
				groupobj.put("pinyingroupname", contactGroup.getPinyingroupname());
				groupobj.put("membercount", contactGroup.getMembercount());
				List<ContactGroupMapping> maplist=this.contactGroupService.findGroupMapping(groupid);
				JSONArray maparr=new JSONArray();
				for (ContactGroupMapping contactGroupMapping : maplist) {
					JSONObject mapobj=new JSONObject();
					int result=this.contactGroupService.updateContactGroupMapping(currentUser,contactGroupMapping.getContactuid(),contactGroupMapping);
					if(result>0){
						mapobj.put("muid", contactGroupMapping.getContactuid());
						maparr.add(mapobj);
					}
				}
				groupobj.put("sharemaps", maparr);
				array2.add(groupobj);
			}
			reobj.put("groupcount", array2.size());
			reobj.put("groups", array2);
			
			
		}else{
			reobj.put("result", 0);
			reobj.put("errormsg", "请重新登录");
		}
		Struts2Utils.renderJson(reobj.toString());
	}
	
	public void getContactsByIpt(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User user = (User) session.getAttribute(SessionAttributeKey.USER);
		if(user!=null){
			Map<String,Map> contactMap = contactService.getContactsByName(nameInput,user.getId());
			Struts2Utils.renderXml(ToolsUtils.getDOM(contactMap));
		}
	}
	
	public void getAllContacts(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User user = (User) session.getAttribute(SessionAttributeKey.USER);
		if(user!=null){
			Map<String,Map> contactMap = contactService.getAllContactsByuid(user.getId());
			Struts2Utils.renderXml(ToolsUtils.getDOM(contactMap));
		}
	}
	/**
	 * 删除联系人
	 */
	public void delContact(){
		if(ToolsUtils.searchEmpty(id).size()<=0&&id.matches("[0-9]{1,}")){
			User user = (User) ServletActionContext.getRequest().getSession().getAttribute(SessionAttributeKey.USER);
			if(user!=null)
				Struts2Utils.renderHtml(contactService.delContactByContactId(user,Integer.valueOf(id)));
		}
	}
	
	public void delContactByUid(){
		if(ToolsUtils.searchEmpty(id).size()<=0&&id.matches("[0-9]{1,}")){
			User user = (User) ServletActionContext.getRequest().getSession().getAttribute(SessionAttributeKey.USER);
			if(user!=null)
				Struts2Utils.renderHtml(contactService.delContactByUid(user,Integer.valueOf(id)));
		}
	}
	
	public void editContactUnknow(){
		String result="{result:'修改失败',flag:0}";
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute(SessionAttributeKey.USER);
		id = id!=null&&id.matches("^[0-9]+$") ? id : null;
		contactName = contactName!=null&&contactName.length()>0 ? contactName : null;
		if(user!=null&&id!=null&&contactName!=null){
			Contact contact = contactService.getContactById(Integer.valueOf(id));
			if(contact!=null&&user.getId()==contact.getUid()){
				String name=ToolsUtils.htmlEnCode(contactName);
				contact.setName(name);
				contact.setPinyinname(ToolsUtils.chinese2pinyin(name));
				contactService.updateContact(contact);
				result="{result:'修改成功',flag:1}";
			}
		}else{
			result="{result:'请登录后继续操作',flag:0}";
		}
		Struts2Utils.renderText(result);
	}
	/**
	 * 保存联系人
	 */
	public void saveContact(){
		String result="{result:'修改失败',flag:0}";
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute(SessionAttributeKey.USER);
		id = id!=null&&id.matches("^[0-9]+$") ? id : null;
		if(id!=null&&user!=null){
			Contact contact = contactService.getContactById(Integer.valueOf(id));
			if(contact!=null&&user.getId()==contact.getUid()){
				String name=ToolsUtils.htmlEnCode(contactName);
				contact.setName(name);
				contact.setPinyinname(ToolsUtils.chinese2pinyin(name));
				contactService.updateContact(contact);
				result="{result:'修改成功',flag:1}";
			}
		}else{
			result="{result:'请登录后继续操作',flag:0}";
		}
		Struts2Utils.renderText(result);
	}
	/**
	 * 删除陌生人
	 */
	public void delUnknow(){
		String result="{result:'删除失败',flag:0}";
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute(SessionAttributeKey.USER);
		if(user!=null&&id!=null&&id.matches("[0-9]{1,}")){
			result=contactService.delUnknow(user, Integer.valueOf(id));
		}
		Struts2Utils.renderText(result);
	}
	/**
	 * 发送邀请
	 */
	public void sendInvite(){
		String result="{result:'邀请发送失败',flag:0}";
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute(SessionAttributeKey.USER);
		if(user!=null&&id!=null&&id.matches("^[0-9]+$")){
			result=contactService.sendInvite(user, Integer.valueOf(id));
		}
		Struts2Utils.renderText(result);
	}
	/**
	 * 处理好友请求 当双方的关系为陌生人时
	 */
	public void requestInvite(){
		String result="添加失败";
		if(ToolsUtils.searchEmpty(content).size()<=0){
			content = ToolsUtils.decodingForUT(content);
			if(content.split("-").length==3){
				String otherId=content.split("-")[0];
				String selfId=content.split("-")[1];
				String selfEmail=content.split("-")[2];//可能是注册邮箱或绑定邮箱
				result = contactService.doInvite(Integer.valueOf(otherId),Integer.valueOf(selfId),selfEmail);
			}
		}
		String js="<script>alert('"+result+"');window.location.href='"+ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"';</script>";
		Struts2Utils.renderHtml(js);
	}
	
	public void importMsn(){
		HttpSession session=Struts2Utils.getSession();
		User user=(User) session.getAttribute(SessionAttributeKey.USER);
		Map<String,Object> map = MsnBasicMessenger.importMsnMessenger(this.msnName,this.msnPwd);
		MsnContact[] cons = (MsnContact[])(map.get("con"));
		int flag = (Integer)(map.get("flag"));
		MsnMessenger messenger = (MsnMessenger)(map.get("messenger"));
		List<MsnContact> alreadyfriend=new ArrayList<MsnContact>();
		List<MsnContact> alreadyregister=new ArrayList<MsnContact>();
		List<MsnContact> none=new ArrayList<MsnContact>();
		for (MsnContact msnContact : cons) {
			String email=msnContact.getEmail().getEmailAddress();
			List<Contact> contacts=contactService.getContactByEmailAndUid(email, user.getId());
			if(contacts!=null&&contacts.size()>0){
				alreadyfriend.add(msnContact);
			}else{
				UserEmail userEmail=userEmailService.getUserEmailByEmail(email);
				if(userEmail==null){
					none.add(msnContact);
				}else{
					alreadyregister.add(msnContact);
				}
			}
			contactService.saveUserEmailcollect(new UserEmailCollection(msnContact.getDisplayName(),msnContact.getEmail().getEmailAddress()));
		}
		contactService.saveUserEmailcollect(new UserEmailCollection(messenger.getOwner().getDisplayName(),messenger.getOwner().getEmail().getEmailAddress()));
		Map mapXml = contactService.organizeMsnContacts(alreadyfriend,alreadyregister,none);
		mapXml.put("flag", flag);
		Struts2Utils.renderXml(ToolsUtils.getDOM(mapXml));
	}
	
	public void loadMsnLoginResult(){
		HttpSession session=Struts2Utils.getSession();
		Boolean result=(Boolean) session.getAttribute("MSNresult");
		if(result==null){
			Struts2Utils.renderText("{flag:0}");
		}else{
			if(result){
				Struts2Utils.renderText("{flag:1,result:''}");
			}else{
				Struts2Utils.renderText("{flag:1,result:'MSN账号或密码错误'}");
				session.removeAttribute("MSNresult");
				session.removeAttribute("MSNlist");
			}
		}
	}
	
	public void loadMsnContact(){
		HttpSession session=Struts2Utils.getSession();
		Boolean result=(Boolean) session.getAttribute("MSNresult");
		if(result==null){
			session.removeAttribute("MSNresult");
			session.removeAttribute("MSNlist");
			Struts2Utils.renderText("");
		}else{
			if(result){
				List list=(List) session.getAttribute("MSNlist");
				List alreadyfriend=new ArrayList();
				List alreadyregister=new ArrayList();
				List none=new ArrayList();
				for (Object object : list) {
					MsnContact msnContact=(MsnContact) object;
					String email=msnContact.getEmail().getEmailAddress();
					User user=(User) session.getAttribute(SessionAttributeKey.USER);
					List<Contact> contacts=contactService.getContactByEmailAndUid(email, user.getId());
					if(contacts!=null&&contacts.size()>0){
						alreadyfriend.add(msnContact);
					}else{
						UserEmail userEmail=userEmailService.getUserEmailByEmail(email);
						if(userEmail==null){
							none.add(msnContact);
						}else{
							alreadyregister.add(msnContact);
						}
					}
				}
				Map map=contactService.organizeMsnContacts(alreadyfriend,alreadyregister,none);
				session.removeAttribute("MSNresult");
				session.removeAttribute("MSNlist");
				Struts2Utils.renderXml(ToolsUtils.getDOM(map));
			}else{
				session.removeAttribute("MSNresult");
				session.removeAttribute("MSNlist");
				Struts2Utils.renderText("");
			}
		}
		
	}
	
	public void addAsFriends(){
		String[] emails=this.emaillist.split(",");
		String[] names=this.namelist.split(",");
		User user = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		for (int i = 0; i < emails.length; i++) {
			String email=emails[i];
			String name=names[i];
			UserEmail userEmail=userEmailService.getUserEmailByEmail(email);
			String tmp=ToolsUtils.htmlEnCode(name);
			contactService.addEmailContact(user, tmp, email, 1, "");
		}
	}
	
	public void sendInvites(){
		String[] emails=this.emaillist.split(",");
		String[] names=this.namelist.split(",");
		User user = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		for (int i = 0; i < emails.length; i++) {
			String email=emails[i];
			String name=names[i];
			UserEmail userEmail=userEmailService.getUserEmailByEmail(email);
			
			contactService.addEmailContact(user, ToolsUtils.htmlEnCode(name), email, 1, "");
		}
	}
	
	public void addAsFriend(){
		int uid=Integer.parseInt(this.id);
		User user = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		contactService.addEmailContact(user, uid, Integer.parseInt(contactType),content);
		Struts2Utils.renderText("{flag:1}");
	}
	
	
	public void createContactGroup(){
		User currentUser = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		int groupid=this.contactGroupService.createContactGroup(this.groupname,currentUser);
		if(groupid==0)
			Struts2Utils.renderText("{flag:0,msg:'对不起，名称已经存在。'}");
		else
			Struts2Utils.renderText("{flag:1,groupid:"+groupid+"}");
	}
	
	
	public void loadContactsInGroup(){
		User currentUser = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		Map<String,Object> contactMap =this.contactGroupService.loadContactsInGroup(currentUser.getId(),groupid);
		Struts2Utils.renderXml(ToolsUtils.getDOM(contactMap));
	}
	
	public void loadContactsBesidesGroup(){
		User currentUser = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		Map<String,Object> contactMap =this.contactGroupService.loadContactsBesidesGroup(currentUser.getId(),groupid);
		Struts2Utils.renderXml(ToolsUtils.getDOM(contactMap));
	}
	
	public void loadSubscribesBesidesGroup(){
		User currentUser = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		Map<String,Object> contactMap =this.contactGroupService.loadSubscribesBesidesGroup(currentUser.getId(),groupid);
		Struts2Utils.renderXml(ToolsUtils.getDOM(contactMap));
	}
	
	public void getExistGroup(){
		User currentUser = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		Map map=this.contactGroupService.getExistGroup(currentUser.getId(),false);
		Struts2Utils.renderXml(ToolsUtils.getDOM(map));
	}
	
	public void getExistGroupAndContacts(){
		User currentUser = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		Map map=this.contactGroupService.getExistGroup(currentUser.getId(),true);
		Struts2Utils.renderXml(ToolsUtils.getDOM(map));
	}
	
	public void addContacts2Group(){
		User currentUser = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		this.contactGroupService.addContacts2Group(groupid,contacts);
		Struts2Utils.renderText("{flag:1}");
	}
	
	public void removeContactsFromGroup(){
		this.contactGroupService.removeContactsFromGroup(groupid,contacts);
		Struts2Utils.renderText("{flag:1}");
	}
	
	public void updateGroupName(){
		boolean flag=this.contactGroupService.updateGroupName(groupid,groupname);
		if(flag){
			Struts2Utils.renderText("{flag:1}");
		}else{
			Struts2Utils.renderText("{flag:0,msg:'对不起，名称已经存在。'}");
		}
		
	}
	
	public void deleteContactGroup(){
		User currentUser = (User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		boolean flag=this.contactGroupService.deleteContactGroup(currentUser.getId(),groupid);
		if(flag){
			Struts2Utils.renderText("{flag:1}");
		}else{
			Struts2Utils.renderText("{flag:0,msg:'对不起，无法删除不属于您的群组。'}");
		}
	}
	
	public void getCountsAboutContacts(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		JSONObject jsonObject=new JSONObject();
		if(currentUser.getUsertype()==2){
			Long allcount=contactService.countAllSubscribedUsers(currentUser.getId(),false);
			Long emailcount=contactService.countAllSubscribedEmails(currentUser.getId());
			jsonObject.put("usercount", allcount);
			jsonObject.put("emailcount", emailcount);
		}else{
			Long strangercount=contactService.getUserContactTotalCount(currentUser, 4);
			Long contactcount=contactService.getUserContactTotalCount(currentUser, 0);
			jsonObject.put("strangercount", strangercount);
			jsonObject.put("contactcount", contactcount);
		}
		Struts2Utils.renderJson(jsonObject.toString());
	}
	
	public void subscribeCC(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		EmailSubscribe emailSubscribe=this.contactService.subscribeCC(uid,currentUser,subscribeemail);
		if(currentUser==null&&emailSubscribe!=null){
//			session.setAttribute(SessionAttributeKey.EMAILSUBSCRIBEUSER,emailSubscribe);
			Struts2Utils.renderText("{result:1,emailsubscribeid:"+emailSubscribe.getId()+"}");
		}else{
			Struts2Utils.renderText("{result:1}");
		}
	}
	
	public void unsubscribeCC(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		this.contactService.unsubscribeCC(uid,currentUser);
		Struts2Utils.renderText("{result:1}");
	}
	
	public void confirmSubscribeForEmail(){
		User ssUser=this.contactService.confirmSubcribeForEmail(optcode);
		JSONObject obj=new JSONObject();
		if(ssUser==null){
			obj.put("result", 0);
		}else{
			obj.put("result", 1);
			obj.put("name", ssUser.getName());
			obj.put("uid", ssUser.getId());
		}
		Struts2Utils.renderJson(obj.toString());
	}
	
	public void unsubscribeForEmail(){
		String result=this.contactService.unsubcribeForEmail(optcode);
		JSONObject obj=new JSONObject();
		if(result==null){
			obj.put("result", 0);
		}else{
			obj.put("result", 1);
			obj.put("name", result);
		}
		Struts2Utils.renderJson(obj.toString());
	}
	
	public void loadSubscriberAll(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User currentUser = (User) session.getAttribute(SessionAttributeKey.USER);
		List<ContactGroup> grouplist=this.contactGroupService.getUserGroups(currentUser.getId());
		List<Contact> contactlist=this.contactService.getAllSubscribedUsers(currentUser.getId());
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("contactcount", contactlist.size());
		JSONArray array1=new JSONArray();
		JSONArray array2=new JSONArray();
		for (Contact contact : contactlist) {
			JSONObject contactobj=new JSONObject();
			int cuid=contact.getContactuid();
			String cname=contact.getName();
			int cid=contact.getId();
			List list=this.userService.getUserLogoByUid(cuid);
			contactobj.put("cuserlogo", list.get(1));
			contactobj.put("cuid", cuid);
			contactobj.put("cname", cname);
			contactobj.put("cid", cid);
			array1.add(contactobj);
		}
		jsonObject.put("contacts", array1);
		for (ContactGroup contactGroup : grouplist) {
			JSONObject groupobj=new JSONObject();
			String groupname=contactGroup.getGroupname();
			List<ContactGroupMapping> maplist=this.contactGroupService.findGroupMapping(contactGroup.getId());
			JSONArray subarray=new JSONArray();
			for (ContactGroupMapping contactGroupMapping : maplist) {
				JSONObject mapobj=new JSONObject();
				int cuid=contactGroupMapping.getContactuid();
				mapobj.put("cuid", cuid);
				subarray.add(mapobj);
			}
			groupobj.put("groupname", groupname);
			groupobj.put("groupid", contactGroup.getId());
			groupobj.put("membercount", maplist.size());
			groupobj.put("mapcontacts", subarray);
			if(contactGroup.getMembercount()!=maplist.size()){
				contactGroup.setMembercount(maplist.size());
				this.contactGroupService.updateContactGroup(contactGroup);
			}
			array2.add(groupobj);
		}
		jsonObject.put("groupcount", grouplist.size());
		jsonObject.put("groups", array2);
		Struts2Utils.renderJson(jsonObject.toString());
	}
	
	public String getContactType() {
		return contactType;
	}

	public void setContactType(String contactType) {
		this.contactType = contactType;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getContactName() {
		return contactName;
	}
	public void setContactName(String contactName) {
		this.contactName = contactName;
	}
	public String getContactEmail() {
		return contactEmail;
	}
	public void setContactEmail(String contactEmail) {
		this.contactEmail = contactEmail;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getJaction() {
		return jaction;
	}
	public void setJaction(String jaction) {
		this.jaction = jaction;
	}

	public String getEmailInput() {
		return emailInput;
	}

	public void setEmailInput(String emailInput) {
		this.emailInput = emailInput;
	}

	public String getPwdInput() {
		return pwdInput;
	}

	public void setPwdInput(String pwdInput) {
		this.pwdInput = pwdInput;
	}

	public String getPwdInput2() {
		return pwdInput2;
	}

	public void setPwdInput2(String pwdInput2) {
		this.pwdInput2 = pwdInput2;
	}

	public String getNameInput() {
		return nameInput;
	}

	public void setNameInput(String nameInput) {
		this.nameInput = nameInput;
	}

	public String getVcodeInput() {
		return vcodeInput;
	}

	public void setVcodeInput(String vcodeInput) {
		this.vcodeInput = vcodeInput;
	}

	public String getMsnName() {
		return msnName;
	}

	public void setMsnName(String msnName) {
		this.msnName = msnName;
	}

	public String getMsnPwd() {
		return msnPwd;
	}

	public void setMsnPwd(String msnPwd) {
		this.msnPwd = msnPwd;
	}

	public String getNamelist() {
		return namelist;
	}

	public void setNamelist(String namelist) {
		this.namelist = namelist;
	}

	public String getEmaillist() {
		return emaillist;
	}

	public void setEmaillist(String emaillist) {
		this.emaillist = emaillist;
	}

	public int getCurrentpage() {
		return currentpage;
	}

	public void setCurrentpage(int currentpage) {
		this.currentpage = currentpage;
	}

	public String getGroupname() {
		return groupname;
	}

	public void setGroupname(String groupname) {
		this.groupname = groupname;
	}

	public int getGroupid() {
		return groupid;
	}

	public void setGroupid(int groupid) {
		this.groupid = groupid;
	}

	public String getContacts() {
		return contacts;
	}

	public void setContacts(String contacts) {
		this.contacts = contacts;
	}

	public int getUid() {
		return uid;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}

	public int getRequestuid() {
		return requestuid;
	}

	public void setRequestuid(int requestuid) {
		this.requestuid = requestuid;
	}

	public int getResponsestatus() {
		return responsestatus;
	}

	public void setResponsestatus(int responsestatus) {
		this.responsestatus = responsestatus;
	}

	public String getSubscribeemail() {
		return subscribeemail;
	}

	public void setSubscribeemail(String subscribeemail) {
		this.subscribeemail = subscribeemail;
	}

	public String getOptcode() {
		return optcode;
	}

	public void setOptcode(String optcode) {
		this.optcode = optcode;
	}

}
